package com.frontop.terminal.vlcjplayer.view.main;

import com.frontop.terminal.vlcjplayer.event.TickEvent;
import com.frontop.terminal.vlcjplayer.view.StandardLabel;
import com.google.common.eventbus.Subscribe;
import net.miginfocom.swing.MigLayout;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.frontop.terminal.vlcjplayer.Application.application;
import static com.frontop.terminal.vlcjplayer.time.Time.formatTime;

final class PositionPane extends JPanel {

    private final JLabel timeLabel;

    private final JSlider positionSlider;

    private final JLabel durationLabel;
    private final AtomicBoolean sliderChanging = new AtomicBoolean();
    private final AtomicBoolean positionChanging = new AtomicBoolean();
    private long time;

    PositionPane() {
        timeLabel = new StandardLabel("99999");
        // FIXME how to do this for a single component?
        UIManager.put("Slider.paintValue", false);
        positionSlider = new JSlider();
        positionSlider.setMinimum(0);
        positionSlider.setMaximum(1000);
        positionSlider.setValue(0);

        positionSlider.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                if (!positionChanging.get()) {
                    JSlider source = (JSlider) e.getSource();
                    sliderChanging.set(source.getValueIsAdjusting());
                    application().mediaPlayer().controls().setPosition(source.getValue() / 1000.0f);
                }
            }
        });

        durationLabel = new StandardLabel("99999");

        setLayout(new MigLayout("fill, insets 0 0 0 0", "[][grow][]", "[]"));

        add(timeLabel, "shrink");
        add(positionSlider, "grow");
        add(durationLabel, "shrink");


        application().subscribe(this);
    }

    private void refresh() {
        timeLabel.setText(String.valueOf(time));

        if (!sliderChanging.get()) {
            int value = (int) (application().mediaPlayer().status().position() * 1000.0f);
            positionChanging.set(true);
            positionSlider.setValue(value);
            positionChanging.set(false);
        }
    }

    void setTime(long time) {
        this.time = time;
    }

    void setDuration(long duration) {
        durationLabel.setText(formatTime(duration));
    }

    @Subscribe
    public void onTick(TickEvent tick) {
        refresh();
    }
}
